﻿package code {
	import flash.display.Sprite;
	import flash.geom.Point;
	// class replicates a spring
	public class Spring extends Sprite{
		
		private var springLength;  // length that the spring is
		private var spring = .95;  // spring constant
		private var friction = .60;  // friction of the spring
		public var fixedPoint;
		public var topFixedPoint;
		public var topPoint;
		public var thickness, color:Number;
		public var a,b:Vertex;
		
		public function Spring(a:Vertex, b:Vertex, thickness:Number, color:Number, fixedPoint:Vertex, bar:Bar) {
			
			this.a = a;
			this.b = b;
			springLength = Math.sqrt(Math.pow((b.x - a.x), 2) + Math.pow((b.y - a.y), 2));
			this.thickness = thickness;
			this.color = color;
			this.fixedPoint = fixedPoint;
		}
		

		// updates location of the spring
		public function update(a:Vertex):void {
			this.a.x = a.x;
			this.a.y = a.y;
		}
		
		// springs to a position and applies force to the ball
		public function springTo(bar:Bar):void
		{
			var springPointX = bar.bottomRightVertex.x;
			var springPointY = bar.bottomRightVertex.y;
			
			var dx:Number = b.x - springPointX;
			var dy:Number = b.y - springPointY;
			var angle:Number = Math.atan2(dy, dx);
			var targetX:Number = b.x - Math.cos(angle) * springLength;
			var targetY:Number = b.y - Math.sin(angle) * springLength;
			
			var springForceX = (targetX - springPointX) * spring;  // force in x direction
			var springForceY = (targetY - springPointY) * spring;  // force in y direction
			
			var springForceVertex = new Vertex(springForceX, springForceY);  // creates vector of the spring force
			
			var displacement:Number = Vertex.displace(bar.topLeftVertex, bar.bottomRightVertex); // gets displacement of lever arm
			
			var torque = displacement * Vertex.getMagnitude(springForceVertex) * Math.sin(angle);  // r*F sin(theta) = r x F

			bar.angAlpha = torque / bar.getInertia(displacement); // torque / I=
			bar.omega *= friction;

		}

	}
	
}
